package com.diaohw.platform.common.constant;

import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.diaohw.platform.common.obj.login.LoginUser;

/**
 * @author 刁海文
 * @Remark
 * @since 2023/6/11 17:51
 */
public interface RequestConstant {
    String AUTHORIZATION = tokenName();
    String REQUEST_ID = "RequestId";
    String LINK_ID = "LinkId";
    String IP = "Ip";
    String LoginId = "loginId";
    String Username = "LoginName";
    String Nickname = "Nickname";

    static String tokenName() {
        String property = SpringUtil.getProperty("sa-token.token-name");
        if (property == null) {
            return "Authorization";
        }
        return property;
    }

    static LoginUser parseToken(String token) {
        if (token == null) return null;
        JWT jwt = JWTUtil.parseToken(token);
        JSONObject payloads = jwt.getPayloads();
        return LoginUser.builder()
                .loginId(payloads.getStr(LoginId))
                .username(payloads.getStr(Username))
                .nickname(payloads.getStr(Nickname))
                .build();
    }

}
